package com.example.springconfig.demos.controller;

import com.example.springconfig.demos.model.User;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.UnsatisfiedServletRequestParameterException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RequestMapping("scope")
@RestController
public class BeanScopeController {
    @Autowired
    private ConfigurableApplicationContext context;

    // 有多个@Autowired的时候,指定名称使用哪个
    @Resource(name = "singleUser")
    private User singleUser;

    @Resource(name = "prototypeUser")
    private User prototypeUser;

    @Resource(name = "requestUser")
    private User requestUser;

    @Resource(name = "sessionUser")
    private User sessionUser;

    @Resource(name = "applicationUser")
    private User applicationUser;

    @RequestMapping("/single")
    public String single(){
         // 1. 从context中获取对象
        User user = (User) context.getBean("singleUser");
        // 2. 属性注入获取对象

        return "从context中获取的对象 " + System.identityHashCode(user)
                + "属性注入获取的对象" + System.identityHashCode(singleUser);
    }

    @RequestMapping("/phototype")
    public String phototype(){
        // 1. 从context中获取对象
        User user = (User) context.getBean("prototypeUser");
        // 2. 属性注入获取对象

        return "从context中获取的对象 " + System.identityHashCode(user)
                + "属性注入获取的对象" + System.identityHashCode(prototypeUser);
    }

    @RequestMapping("/request")
    public String request(){
        // 1. 从context中获取对象
        User user = (User) context.getBean("requestUser");
        // 2. 属性注入获取对象

        return "从context中获取的对象 " + user
                + "属性注入获取的对象" + requestUser;
    }

    @RequestMapping("/session")
    public String session(){
        // 1. 从context中获取对象
        User user = (User) context.getBean("sessionUser");
        // 2. 属性注入获取对象

        return "从context中获取的对象 " + System.identityHashCode(user)
                + "属性注入获取的对象" + System.identityHashCode(sessionUser);
    }

    @RequestMapping("/application")
    public String application(){
        // 1. 从context中获取对象
        User user = (User) context.getBean("applicationUser");
        // 2. 属性注入获取对象

        return "从context中获取的对象 " + user
                + "属性注入获取的对象" + applicationUser;
    }
}
